<script lang="ts" setup>
import { onBeforeUnmount, onMounted, reactive, watch, ref } from 'vue';
//  defineProps,
import { useRouter } from 'vue-router';
import {
  ElMessage,
  ElInput,
  ElButton,
} from "element-plus";
import { openWindow } from '@vben/utils';
import { reactify } from '@vueuse/core';
import Controls from 'xgplayer/es/plugins/controls';
import AMapLoader from "@amap/amap-jsapi-loader";
import { mapSetting } from "#/api/map";
import { getMapInstance } from '#/utils/mapSingleton';
const getImageUrl = (name: string) => {
  return new URL(`../../../../../assets/${name}`, import.meta.url).href
}
// import { mapKey } from '/static/mapKey.js'
// console.log(mapKey)
const props = defineProps({ airportList: Array, loading: Boolean });
const router = useRouter();
const to_info = (item) => {
  router.push({
    name: 'AirportdeploymentDetail',
    query: { id: item.id },
  });
};
// const navToClick = () => {
//   const nav = '/dronemonitoringDetail';
//   if (nav?.startsWith('http')) {
//     openWindow(nav);
//     return;
//   }
//   if (nav?.startsWith('/')) {
//     router.push(nav).catch((error) => {
//       console.error('Navigation failed:', error);
//     });
//   } else {
//     console.warn(`Unknown URL for navigation item: ${nav.title} -> ${nav.url}`);
//   }
// };
const markers = reactive([])
const mapContainer = ref(null)
// const AMapInstance = ref(null); // 保存AMap实例
let map;
let centerlnglat = [119.904792, 30.247956];
const loadAMap = async () => {
  // return new Promise((resolve, reject) => {
  //   if (window.AMap) {
  //     resolve(window.AMap);
  //     return;
  //   }
  //   const script = document.createElement('script');
  //   script.src = `https://webapi.amap.com/maps?v=2.0&key=ce77626588b7a2ee836159f48dd4a1a6`;
  //   // script.src = mapKey
  //   script.addEventListener('load', () => resolve(window.AMap));
  //   script.onerror = reject;
  //   document.head.append(script);
  // });
  console.log(AMapLoader)
  try {
    await AMapLoader.load({
      key: mapSetting.mapKey,
      securityJsCode: mapSetting.mapSecurity,
      version: "2.0",
      plugins: [
        "AMap.AutoComplete",
        "AMap.ToolBar",
        "AMap.Scale",
        "AMap.Marker",
      ],
    });
    if (props.airportList && props.airportList[0]) {
      centerlnglat = [props.airportList[0].longitude, props.airportList[0].latitude];
      // 保存AMap实例以便在其他函数中使用
      // AMapInstance.value = AMap;
      // 设置地图中心点
      // if (props.airportList[0]) {
      //   console.log([props.airportList[0].longitude, props.airportList[0].latitude])
      //   AMap.convertFrom([props.airportList[0].longitude, props.airportList[0].latitude], 'gps', function (status, result) {
      //     console.log(status, result)
      //     if (result.info === 'ok') {
      //       centerlnglat = result.locations;
      //       setMap()
      //     }
      //   });
      // } else {
      //   setMap()
    }
    setMap()
  } catch (error) {
    console.error("地图初始化失败:", error);
    // ElMessage.error("地图初始化失败: " + error.message);
  }
};
const setMap = () => {
  // 创建地图实例
  // console.log(centerlnglat)

  if (!map) {
    map = new AMap.Map(mapContainer.value, {
      zoom: 15,
      center: centerlnglat,
      pitch: 60, // 俯仰角度
      viewMode: '3D', // 启用 3D 模式
      layers: [
        // 卫星
        new AMap.TileLayer.Satellite(),
        // 路网
        new AMap.TileLayer.RoadNet(),
      ],
    });
  }
  // 加载机场位置点
  if (props.airportList.length > 0) {
    for (let item of props.airportList) {
      const marker = new AMap.Marker({
        position: [item.longitude, item.latitude],
        title: item.airportName,
        icon: new AMap.Icon({
          image: getImageUrl('airport_logo2.png'),
          // '../../../../../assets/'
          size: new AMap.Size(48, 48),
          imageSize: new AMap.Size(48, 48),
        }),
        offset: new AMap.Pixel(-24, -24),
        autoRotation: false,
        extData: item
      })
      marker.on("click", function (e) {
        const data = marker.getExtData()
        router.push({
          name: 'AirportdeploymentDetail',
          query: { id: data.id },
        });
      });
      markers.push(marker)
      map.add(marker);
    }
    map.setFitView()
  }
}
onMounted(async () => {
  try {
    await loadAMap();
    // if (!map) {
    //   map = new AMap.Map('map-container', {
    //     zoom: 15,
    //     center: centerlnglat,
    //     pitch: 60, // 俯仰角度
    //     viewMode: '3D', // 启用 3D 模式
    //     layers: [
    //       // 卫星
    //       new AMap.TileLayer.Satellite(),
    //       // 路网
    //       new AMap.TileLayer.RoadNet(),
    //     ],
    //   });
    // }
    // if (props.airportList.length > 0) {
    //   for (let item of props.airportList) {
    //     const marker = new AMap.Marker({
    //       position: [item.longitude, item.latitude],
    //       title: item.airportName,
    //       extData: item
    //     })
    //     marker.on("click", function (e) {
    //       const data = marker.getExtData()
    //       router.push({
    //         name: 'AirportdeploymentDetail',
    //         query: { id: data.id },
    //       });
    //     });
    //     markers.push(marker)
    //     map.add(marker);
    //   }
    //   map.setFitView()
    // }
  } catch (error) {
    console.error('地图加载失败:', error);
  }
});
onBeforeUnmount(() => { });
</script>
<template>
  <div class="air-map">
    <div id="map-container" ref="mapContainer" class="map"></div>
  </div>
</template>

<style lang="scss" scoped>
.air-map {
  position: relative;
  box-sizing: border-box;
  height: calc(100% - 2px);
  overflow: hidden;

  :deep(.amap-logo) {
    display: none !important;
  }

  :deep(.amap-copyright) {
    display: none !important;
  }

  // margin: 0.5rem 0;
  // border: 1px solid #fff;
  .map {
    position: absolute;
    right: 0;
    bottom: 0;
    left: 0;
    width: 100%;
    height: calc(100% + 200px);
  }
}
</style>
